import { defineComponent, ref, VNode, PropType, watch, getCurrentInstance } from 'vue'

/* scss */
import '@src/modules/intelligentQuality/views/newInfo/components/index.scss'
/* utils */
import { message } from '@src/util/message'
import Uploader from 'packages/BaseUpload/uploader';
import state from '@src/modules/intelligentQuality/utils/state.ts'
/* hooks */
import { useCurrentInstance } from '@src/modules/intelligentQuality/hooks'
/* components */
import RenameDialog from '@src/modules/intelligentQuality/views/components/renameDialog/index.tsx'

interface uploadFileList {
    picId: string,
    fileId: string,
    ossUrl: string,
    fileName: string,
    fileSizeStr: string
}

export default defineComponent({
    name: 'stepSettingPhoto',
    props: {
        examplePicList: {
            type: Array as PropType<uploadFileList[]>,
            default: () => []
        }
    },
    emits: ['change'],
    setup(props, { emit }) {
        const uploadFileList = ref<uploadFileList[]>(props.examplePicList)
        const supportFileType = ['JPEG', 'JPG', 'PNG', 'BMP']
        const loading = ref(false)
        const [currentCtx] = useCurrentInstance()
        const renameDialogRef = ref<InstanceType<typeof RenameDialog> | null>(null)
        // 正在上传的列表数据
        const base64List = ref<any[]>([])
        const base64ListFlag = ref(false)

        /**
         * @description 文件上传处理函数
         * @param file 
         * @param fileList 
         */
        const intelligenceFileUpload = async (file: any, fileList: any) => {
            const fileType = file.raw.type.split('/')[1].toUpperCase();
            if (!supportFileType.includes(fileType)) {
                message.warn('不支持的文件类型');
                return;
            }

            try {
                base64ListFlag.value = true
                const base64 = await rawToBase64(file.raw)
                base64List.value.push({
                    url: base64,
                    fileName: file.raw.name,
                    progress: 0
                })
                simulateProgress(base64List.value.length - 1)
            } catch (error) {
                console.log(error)
            }

            Uploader.upload(file.raw, '/files/upload')
            .then((result: any) => {
                if (result.status == 0) {
                    uploadFileList.value.push({
                        picId: '',
                        fileId: result.data.id,
                        ossUrl: result.data.ossUrl,
                        fileName: result.data.fileName,
                        fileSizeStr: result.data.fileSizeStr,
                    })
                    message.success("文件上传成功")
                    base64List.value.shift()
                    // base64List.value = []
                } else {
                    message.error('上传失败');
                }
                base64ListFlag.value = false
            }).catch((err: any) => {
                message.error('上传失败');
            }).finally(() => {
                base64ListFlag.value = false
            })
        }

        const simulateProgress = (index: number) => {
            const interval = setInterval(() => {
                if (base64List.value[index].progress < 99) {
                    base64List.value[index].progress += 3;
                    if (base64List.value[index].progress >= 99) {
                        base64List.value[index].progress = 99; // 确保 progress 不超过 99
                        clearInterval(interval);
                    }
                } else {
                    base64List.value[index].progress = 99; // 确保 progress 不超过 99
                    clearInterval(interval);
                }
            }, 500);
        };

        const rawToBase64 = (file: any) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            });
        }


        /**
         * @description 移除文件处理函数
         * @param file 
         * @param fileList 
         */
        const intelligenceRemoveFile = (file: any) => {
            currentCtx.$confirm('确定删除该图片吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                uploadFileList.value = uploadFileList.value.filter(item => item.fileId !== file.fileId)
            }).catch((err) => {
                console.error(err)
            })
        }

        /**
         * @description 图片预览功能
         * @param url 
         */
        const previewImgHandler = (url: string) => {
            currentCtx.$previewElementImg(url)
        }

        /**
         * @description 重命名弹窗处理函数
         * @param file 
         */
        const renameDialogHandler = (file: any) => {
            if (!renameDialogRef.value) return
            (renameDialogRef.value).renameFormData.name = file.fileName.split('.')[0];
            (renameDialogRef.value).renameFormData.id = file.fileId;
            (renameDialogRef.value).showDialog();
        }

        /**
         * @description 重命名弹窗确认处理函数
         * @param data 
         */
        const handleConfirm = (data: {id: string, name: string}) => {
            uploadFileList.value = uploadFileList.value.map(item => {
                if (item.fileId === data.id) {
                    item.fileName = data.name + '.' + item.fileName.split('.')[1]
                }
                return item
            })
        }

        watch(() => uploadFileList.value, (val) => {
            if (val) {
                emit('change', uploadFileList.value)
            }
        }, { immediate: true, deep: true })
        return {
            base64List,
            base64ListFlag,
            renameDialogRef,
            uploadFileList,
            intelligenceFileUpload,
            intelligenceRemoveFile,
            loading,
            previewImgHandler,
            renameDialogHandler,
            handleConfirm
        }
    },
    render() {
        return (
            <div class="setp-setting-photo" v-loading={this.loading}>
                <div class="setp-setting-photo-title">
                    请设置机器人对比图库
                </div>
                <div class="setp-setting-photo-desc">
                    图片格式要求：JPEG/JPG/PNG/BMP，尺寸要求：最短边超过100px，最大边小于2048px
                </div>
                <el-upload
                    class="setp-setting-photo-upload"
                    drag
                    multiple
                    action="" // 不需要实际的上传 URL
                    accept=".jpeg,.jpg,.png,.bmp"
                    {
                        ...{
                            props: {
                                'on-change': this.intelligenceFileUpload,
                                'on-remove': this.intelligenceRemoveFile,
                            }
                        }
                    }
                    show-file-list={false}
                    auto-upload={false}
                >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
                <div class="preview-list">
                    {
                        this.uploadFileList.length !== 0 &&  this.uploadFileList.map(item => {
                            return (
                                <div class="preview-item">
                                    <div class="preview-left">
                                        <div class="preview-left-icon" onClick={() => this.previewImgHandler(item.ossUrl)}>
                                            <img src={item.ossUrl} alt={item.fileName} class="preview-img"/>
                                        </div>
                                        <div class="preview-left-content">
                                            <div class="preview-left-title">{item.fileName}</div>
                                            <div class="preview-left-action">
                                                <span class="preview-left-action-size">{item.fileSizeStr}</span>
                                                <span class="preview-left-action-rename" onClick={(e) => {
                                                    e.stopPropagation()
                                                    this.renameDialogHandler(item)
                                                }}>重命名</span>
                                                <span class="preview-left-action-delete" onClick={(e) => {
                                                    e.stopPropagation()
                                                    this.intelligenceRemoveFile(item)
                                                }}>删除</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )
                        })
                    }
                    {
                        this.base64ListFlag &&  this.base64List.map(item => {
                            return (
                                <div class="preview-item">
                                    <div class="preview-left">
                                        <div class="preview-left-icon" onClick={() => this.previewImgHandler(item.url)}>
                                            <img src={item.url} alt={item.fileName} class="preview-img"/>
                                        </div>
                                        <div class="preview-left-content">
                                            <div class="preview-left-title">{item.fileName}</div>
                                            <div class="preview-left-progress" style={{'--progress-width': `${item.progress}%`}}>
                                                <div class="preview-left-progress-bar"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )
                        })
                    }
                </div>
                <RenameDialog ref={el => this.renameDialogRef = el} onConfirm={(data: any) => this.handleConfirm(data)}/>
            </div>
        ) as unknown as VNode;
    }
})